package com.lingtianyu.tech.springcloud.grayzone.grey.filter;

import com.lingtianyu.tech.springcloud.grayzone.grey.context.GreyContext;
import com.lingtianyu.tech.springcloud.grayzone.grey.loadbalancer.GreyLoadBalancerClient;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GreyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        GreyContext.clear();
        String springcloudGreyZone = getSpringcloudGreyZone(request);
        if (springcloudGreyZone != null && !springcloudGreyZone.isEmpty()) {
            GreyContext.setSpringCloudZone(springcloudGreyZone);
        }
        return true;
    }

    private String getSpringcloudGreyZone(HttpServletRequest request) {
        String zoneName = request.getHeader(GreyLoadBalancerClient.ZONE_NAME);
        if (zoneName == null || zoneName.isEmpty()) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (GreyLoadBalancerClient.ZONE_NAME.equals(cookie.getName())) {
                        zoneName = cookie.getValue();
                        break;
                    }
                }
            }
        }
        return zoneName;
    }
}
